<template>
    <div class="result">
        <ul>
            <li v-for="(song,index) in result" :key="index">
                <SongItem :item="song" :keywords="keywords"></SongItem>
            </li>
        </ul>
        <Loading v-if="isLoading"></Loading>
        <p class="loadMore" @click="addMore" v-show="!isLoading">{{ nomore ? "已经到底咯" : "点击加载更多..." }}</p>
    </div>
</template>

<script>
import SongItem from '@/components/SongItem'
import Loading from '@/components/Loading'
export default {
    name: 'SearchResult',
    props: ['keywords'],
    components: {
        SongItem,
        Loading
    },
    data(){
        return{
            result: [],
            page: 1,
            isLoading:true,
            nomore: false
        }
    },
    created(){
        this.loadSearch();
        window.addEventListener("scroll", this.handleScroll);
    },
    methods:{
        // 加载搜索结果
        loadSearch(){
            this.$http.get('/search?keywords='+this.keywords+'&type=1&offset='+(this.page-1)*30).then(data => {
                this.isLoading = false;
                // console.log(data);
                this.result = this.result.concat(data.data.result.songs);
                this.changeColor(this.result);
            }).catch(err=>{
                console.log(err);
            });
        },
        addMore(){
            this.page++;
            // console.log(this.page);
            // console.log(this.songTotla);
            if (this.page>Math.ceil(parseInt(this.songTotla)/10)) {
                    //如果大于总页数停止请求数据
                    this.nomore = true;
                    return false;
                } else {
                    this.loadSearch();
                    this.isLoading = true;
                }
        },
        changeColor (resultsList) {
            resultsList.map((item, index) => {
            // console.log('item', item)
            if (this.keywords && this.keywords.length > 0) {
                // 匹配关键字正则 g关键词全局匹配 i关键词大小写
                let replaceReg = new RegExp(this.keywords, 'gi');
                // console.log(replaceReg);
                // 高亮替换v-html值
                // 例：汪峰     峰=> <span style="color:red">峰</span>
                let replaceString ='<span class="highlight">' + this.keywords + '</span>';
                resultsList[index].artists[0].name = item.artists[0].name.replace(replaceReg, replaceString);
                resultsList[index].name = item.name.replace(replaceReg, replaceString);
                resultsList[index].album.name = item.album.name.replace(replaceReg,replaceString);
            }
            })
            this.result = resultsList;
      },
    },
    destroyed() {
        window.removeEventListener("scroll", this.handleScroll, false);
    },
}
</script>
<style lang="less" scoped>
.result{
    padding-left:10px;
}
.loadMore{
    padding: 10px 0px;
    text-align: center;
    color: #df3436;
}
</style>